package kr.or.kead.ui.list.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

import com.mysql.jdbc.ResultSetInternalMethods;

import kr.or.kead.utils.MySqlCon;


public abstract class AbsCustomTableModel extends AbstractTableModel {
	private String[] tablecolumnNames;
	private Class[] tablecolumnClasses;
	private Object[] data;
	protected ArrayList<Object[]> arData;
	protected String sql;
	
	
	@Override
	public int getColumnCount() {
		return tablecolumnNames.length;
	}

	@Override
	public int getRowCount() {
		return arData.size();
	}

	@Override
	public Class<?> getColumnClass(int col) {
		return tablecolumnClasses[col];
	}
	
	public void getResultSet(){
		Connection con = MySqlCon.getConn();
		PreparedStatement pstmt = null;
		arData=new ArrayList<>();
		ResultSet rs = null;
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			ResultSetMetaData rsMeta = rs.getMetaData();
			int columnCount = rsMeta.getColumnCount();
			tablecolumnNames = new String[columnCount];
			tablecolumnClasses = new Class[columnCount];
			for(int i = 1; i<=columnCount; i++){
				tablecolumnNames[i-1] = rsMeta.getColumnLabel(i);
				tablecolumnClasses[i-1] = Class.forName(rsMeta.getColumnClassName(i));
			}
			while(rs.next()){
				data = new Object[columnCount];
				for(int i=1; i<=columnCount; i++)
					data[i-1]=rs.getObject(i);
				arData.add(data);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (SQLException e) {
					e.printStackTrace();
			}
		}
	}

	public void refreshData(){
		getResultSet();
		fireTableDataChanged();
	}
	
	public String getColumnName(int col){
		return tablecolumnNames[col];
	}
}
